<?php

/**
 * @author Eureka
 */
class Social
{

	protected $facebook;
	protected $user;
	protected $userID;
	protected $fbID;
	protected $signedRequest;
	protected $isAuthorized;
	private static $_instance;

	public static function getInstance()
	{
		if (is_null(self::$_instance))
		{
			self::$_instance = new self();
		}

		return self::$_instance;
	}

	//put your code here
	public function __construct()
	{
		$config = array(
			'appId' => Config::params('appId'),
			'secret' => Config::params('secret'),
		);
		$this->facebook = new Facebook($config);

		$this->_isAuthorized();
	}

	private function _isAuthorized()
	{
		$signed_request = Yii::app()->request->getParam('signed_request');

		if (!empty($signed_request) && empty($_RESQUEST['signed_request']))
		{
			$_RESQUEST['signed_request'] = $signed_request;
			setcookie("signed_request", $signed_request, time()+3600);
		}
		
		$access_token = Yii::app()->request->getParam('access_token');
		
		if (!empty($access_token) && empty($_REQUEST['access_token']))
		{
			$_REQUEST['access_token'] = $access_token;
			setcookie("access_token", $access_token, time()+3600);
		}
		
		$this->signedRequest = $this->facebook->getSignedRequest();

		$this->fbID = $this->facebook->getUser();

		if ($this->fbID)
		{
			$this->_updateUser();
			$this->isAuthorized = true;
		}
		else
		{
			$this->_isAuthorized = false;
		}
	}

	public function authorize()
	{
		if (empty($this->fbID))
		{
			Util::topRedirect($this->getAuthorizeUrl());
			exit(0);
		}
	}

	public function getUser()
	{
		return $this->user;
	}

	private function _updateUser()
	{
		$user = Users::model()->find('fb_id = :fb_id', array(':fb_id' => $this->fbID));

		if (empty($user))
		{
			$user_profile = $this->facebook->api('/me');
			$user = new Users();
			$user->fb_id = $user_profile['id'];
			$user->full_name = $user_profile['name'];
			$user->link = $user_profile['link'];
			$user->gender = $user_profile['gender'];
			$user->email = @$user_profile['email'];
			$user->created_time = time();
			$user->save();
		}
		$this->user = $user;
		$this->userID = $user['id'];
	}

	public function isLiked()
	{
		if (isset($this->signedRequest['page']))
		{
			return $this->signedRequest['page']['liked'];
		}
		return false;
	}

	public function getAuthorizeUrl()
	{
		return "https://www.facebook.com/dialog/oauth?client_id=" . $this->getAppId()
		. "&redirect_uri=" . $this->getRedirectUrl()
		. "/&scope=" . $this->getOAuthScope();
	}

	public function getRedirectUrl()
	{
		//return $this->getHome() . Config::params('redirectUrl');
		return 'http://apps.facebook.com/yeuhandmade';
	}

	public function getAppId()
	{
		return Config::params('appId');
	}

	public function getOAuthScope()
	{
		return Config::params('oAuthScope');
	}

	public static function getHome()
	{
		return ($_SERVER['HTTP_X_FORWARDED_PROTO'] ? : "http") . "://" . $_SERVER['HTTP_HOST'] . "/";
	}

}
